<template>
  <div>
    <px-row style="min-height: 64px">
      <px-col :span="24" class="water_col">
        <div class="waterdom borderRidus" style="padding-bottom: 0">
          <!-- <div style="width: 100%; height: 64px">
            
          </div> -->
          <px-tabs
            v-model="activeWater"
            class="equipment-tabs"
            style="float: left; width: 540px; margin-top: -10px; background: none"
            @tab-change="setactive"
          >
            <px-tab-pane v-for="(item, index) in tabPaneList" :key="index" :name="item.name">
              <template #label>
                <p class="pane-bottom">{{ item.label }}</p>
                <p class="pane-line" />
              </template>
            </px-tab-pane>
          </px-tabs>
          <px-form ref="queryRef" class="custom-form-ui" :model="queryParams" :inline="true" label-width="120px">
            <px-form-item label="时间维度" style="width: 160px !important">
              <px-select v-model="queryParams.dimension" placeholder="请选择" style="width: 100px" filterable @change="setdimension">
                <px-option v-for="dict in dimensionList" :key="dict.itemValue" :label="dict.itemName" :value="dict.itemValue" />
              </px-select>
            </px-form-item>
            <px-form-item v-if="queryParams.dimension == 'Y'" label="年份">
              <!-- <px-date-picker v-model="queryParams.Time" type="year" placeholder="请选择" /> -->
              <yearPicker :labelWidth="0" :disabledYear="2023" labelText="" :initYear="dateValue" @updateTimeRange="updateStatisticYear" />
            </px-form-item>
            <px-form-item v-if="queryParams.dimension == 'M'" label="月份">
              <px-date-picker
                v-model="queryParams.Time1"
                type="monthrange"
                range-separator="-"
                start-placeholder="开始月份"
                end-placeholder="结束月份"
                placeholder="请选择"
                format="YYYY-MM"
                value-format="YYYY-MM"
                :disabled-date="disabledDate"
                @change="settime"
              />
            </px-form-item>
            <!-- <px-form-item label="时间">
              <px-date-picker v-model="queryParams.Time2" type="datetimerange" range-separator="-"
                start-placeholder="开始时间" end-placeholder="结束时间" placeholder="请选择" format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss" @change="settime2" />
            </px-form-item> -->
            <px-form-item label="厂区" style="width: 190px !important">
              <px-select v-model="queryParams.lev" :disabled="foredisbled" placeholder="请选择厂区" clearable style="width: 150px" filterable>
                <px-option v-for="dict in liquidList" :key="dict.itemValue" :label="dict.itemName" :value="dict.itemValue" />
              </px-select>
            </px-form-item>
            <px-form-item label="核算边界">
              <px-select v-model="queryParams.templateId" placeholder="请选择" style="width: 180px" filterable>
                <px-option v-for="dict in typeList" :key="dict.id" :label="dict.templateName" :value="dict.id" />
              </px-select>
            </px-form-item>
            <px-button style="margin-top: -17px" type="primary" icon="" @click="handleQuery()">查询</px-button>
            <px-button style="margin-top: -17px" icon="" @click="resetQuery">重置</px-button>
          </px-form>
        </div>
      </px-col>
    </px-row>
    <!-- <div v-if="activeWater == 'visual'">
      <visual :visualData="visualData" />
    </div> -->
    <div v-if="activeWater == 'first'">
      <px-row style="height: 340px; margin-top: 16px" :gutter="16">
        <px-col :span="8" class="water_col">
          <div class="waterdom borderRidus">
            <modelTitle :title="'tCO₂e总量'" />
            <div class="model_chart">
              <img class="co2img" src="@/assets/images/tanpaifangfenxi.png" />
              <p class="titlep">排放总量</p>
              <div class="titlevalue">
                <p class="titlevalue1">{{ allData?.total }}<span class="titlevalue1span"> tCO₂e</span></p>
                <p v-if="queryParams.dimension != 'Y'" class="titlevalue2">
                  同比
                  <span :style="{ color: allData?.totalYoy > 0 ? '#F87171' : '#34D399' }">
                    {{ allData?.totalYoy != null ? allData?.totalYoy : "-" }}%</span
                  >
                  <px-icon v-if="allData?.totalYoy > 0" style="margin-top: 8px" color="#F87171">
                    <Top />
                  </px-icon>
                  <px-icon v-if="allData?.totalYoy < 0" style="margin-top: 8px" color="#39c670">
                    <Bottom />
                  </px-icon>
                </p>
              </div>
              <div class="co2mian">
                <div v-for="(item, index) in allData?.factory" :key="index" class="co2mianleft">
                  <p class="co2mianleftp">{{ item?.name }}</p>
                  <p class="co2mianleftp2" style="font-weight: 400">
                    <span class="co2mianleftp2name">排放总量：</span><br />{{ item.value }}<span class="co2mianleftp2span"> tCO₂e</span>
                  </p>
                  <p v-if="queryParams.dimension != 'Y'" class="co2mianleftp3" style="width: 100%">
                    <span style="display: inline-block; width: 70px">同比:</span
                    ><span :style="{ color: item?.yoy > 0 ? '#F87171' : '#34D399' }"> {{ item?.yoy != null ? `${item?.yoy}%` : "-" }}</span>
                    <px-icon v-if="item?.yoy > 0" style="display: inline-block; margin-top: 2px" color="#F87171">
                      <Top />
                    </px-icon>
                    <px-icon v-else-if="item?.yoy < 0" style="display: inline-block; margin-top: 2px" color="#39c670">
                      <Bottom />
                    </px-icon>
                    <px-icon v-else style="display: inline-block; margin-top: 2px" />
                  </p>

                  <p class="co2mianleftp2" style="font-weight: 400">
                    <span class="co2mianleftp2name">占比：</span>{{ item.ratio }}<span class="co2mianleftp2name">%</span>
                  </p>
                </div>
              </div>
            </div>
          </div>
        </px-col>
        <px-col :span="8" class="water_col">
          <div class="waterdom borderRidus">
            <modelTitle :title="'tCO₂e类别占比'" />
            <div class="model_chart">
              <px-table :data="firstCenterData" :border="false" stripe style="width: 100%; overflow-x: hidden" height="212">
                <px-table-column label="类别">
                  <template #default="scope">
                    <span>{{ scope.row.name }}</span>
                  </template>
                </px-table-column>
                <px-table-column label="占比">
                  <template #default="scope">
                    <span>{{ scope.row.ratio ? `${scope.row.ratio}%` : "" }}</span>
                  </template>
                </px-table-column>
                <px-table-column label="排放量tCO₂e">
                  <template #default="scope">
                    <span>{{ scope.row.value }}</span>
                  </template>
                </px-table-column>
                <px-table-column v-if="queryParams.dimension != 'Y'" label="同比">
                  <template #default="scope">
                    <span>{{ scope.row.yoy ? `${scope.row.yoy}%` : "" }}</span>
                  </template>
                </px-table-column>
              </px-table>
            </div>
          </div>
        </px-col>
        <px-col :span="8" class="water_col">
          <div class="waterdom borderRidus">
            <modelTitle :title="'tCO₂e单位产量'" />
            <div class="model_chart">
              <img class="co2img" src="@/assets/images/chip.png" />
              <p class="titlep">每PCS排放</p>
              <div class="titlevalue">
                <p class="titlevalue1">{{ avgData?.avg }}<span class="titlevalue1span"> tCO₂e</span></p>
                <p v-if="queryParams.dimension != 'Y'" class="titlevalue2">
                  同比
                  <span :style="{ color: avgData?.avgYoy > 0 ? '#F87171' : '#34D399' }"> {{ avgData?.avgYoy != null ? avgData?.avgYoy : "-" }}%</span>
                </p>
                <px-icon v-if="avgData?.avgYoy > 0" style="margin-top: 8px" color="#F87171">
                  <Top />
                </px-icon>
                <px-icon v-if="avgData?.avgYoy < 0" style="margin-top: 8px" color="#39c670">
                  <Bottom />
                </px-icon>
              </div>
              <div class="co2mian" style="margin-left: 30px">
                <div>
                  <span class="divcolor" />
                  <span
                    >其中{{ avgData?.maxMonth ? avgData?.maxMonth.slice(0, 7) : "" }}单位产量tCO₂e最高：<span style="color: #3b82f6"
                      >{{ avgData?.max }}
                    </span>
                    tCO₂e</span
                  >
                </div>
                <div style="margin-top: 16px">
                  <span class="divcolor" />
                  <span
                    >其中{{ avgData?.minMonth ? avgData?.minMonth.slice(0, 7) : "" }}单位产量tCO₂e最低：<span style="color: #3b82f6"
                      >{{ avgData?.min }}
                    </span>
                    tCO₂e</span
                  >
                </div>
              </div>
            </div>
          </div>
        </px-col>
      </px-row>
      <px-row style="height: 364px; margin-top: 16px" :gutter="16">
        <px-col :span="12" class="water_col">
          <div class="waterdom borderRidus" style="position: relative">
            <modelTitle :title="'tCO₂e同比'" />
            <!-- <px-button type="primary" style="position: absolute; top: 16px; right: 32px" plain @click="handleExportall">导出</px-button> -->
            <div class="title-right">
              <px-tooltip effect="dark" content="导出图片">
                <px-button type="primary" text :icon="Download" @click="exportImageHandler('chartswwt7Ref')" />
              </px-tooltip>
              <px-tooltip effect="dark" content="导出数据">
                <px-button type="primary" text :icon="Document" @click="handleExportall" />
              </px-tooltip>
            </div>
            <div class="model_chart" style="margin-top: 16px">
              <chartswwt7
                ref="chartswwt7Ref"
                :dimension="queryParams.dimension"
                :chartvalue="allData?.trend"
                style="width: 100%"
                :width="'100%'"
                :height="'270px'"
                @getPieData="setgetPieData"
              />
            </div>
          </div>
        </px-col>
        <px-col :span="12" class="water_col">
          <div class="waterdom borderRidus" style="position: relative">
            <modelTitle :title="'单位tCO₂e同比'" />
            <div class="title-right">
              <px-tooltip effect="dark" content="导出图片">
                <px-button type="primary" text :icon="Download" @click="exportImageHandler('chartswwt7Ref_1')" />
              </px-tooltip>
              <px-tooltip effect="dark" content="导出数据">
                <px-button type="primary" text :icon="Document" @click="handleExportavg" />
              </px-tooltip>
            </div>
            <div class="model_chart" style="margin-top: 16px">
              <chartswwt7
                ref="chartswwt7Ref_1"
                :dimension="queryParams.dimension"
                :chartvalue="avgData?.productionTrend"
                style="width: 100%"
                :width="'100%'"
                :height="'270px'"
              />
            </div>
          </div>
        </px-col>
      </px-row>
    </div>
    <div v-if="activeWater == 'two'">
      <px-row style="margin-top: 16px">
        <px-col :span="24" class="water_col">
          <px-scrollbar class="waterdom borderRidus" @wheel.prevent="onWheel">
            <modelTitle :title="'tCO₂e溯源'" />
            <div style="margin-top: 10px">
              <px-button :icon="Plus" circle @click="bigimg" />
              <px-button :icon="Minus" circle @click="smailimg" />
            </div>
            <div class="title-right" style="right: 32px">
              <px-tooltip effect="dark" content="导出图片">
                <px-button type="primary" text :icon="Download" @click="exportImageHandler('chartsUpwChemistryRef')" />
              </px-tooltip>
              <px-tooltip effect="dark" content="导出数据">
                <px-button type="primary" text :icon="Document" @click="handleExport31()" />
              </px-tooltip>
            </div>
            <div
              :style="{
                scale: imgscale
              }"
              class="model_chart"
              style="min-height: 600px; margin-top: 36px; transform-origin: 50% 0"
            >
              <chartsUpwChemistry ref="chartsUpwChemistryRef" :chartvalue="sanjiValue" width="'100%'" :height="'600px'" />
            </div>
          </px-scrollbar>
        </px-col>
      </px-row>
    </div>
    <div v-if="activeWater == 'three'">
      <px-row style="height: 340px; margin-top: 16px" :gutter="16">
        <px-col :span="12" class="water_col">
          <div class="waterdom borderRidus" style="position: relative">
            <px-button
              v-show="firstDataflg"
              style="position: absolute; top: 20px; right: 100px"
              size="small"
              type="primary"
              plain
              @click="gobackpiedata"
              >返回</px-button
            >
            <px-button
              v-show="twoDataflg"
              style="position: absolute; top: 20px; right: 100px"
              size="small"
              type="primary"
              plain
              @click="gobackpiedata2"
              >返回</px-button
            >
            <modelTitle :title="'tCO₂e类别占比'" />
            <div class="title-right" style="right: 32px">
              <px-tooltip effect="dark" content="导出图片">
                <px-button type="primary" text :icon="Download" @click="exportImageHandler('chartswwt2Ref')" />
              </px-tooltip>
              <px-tooltip effect="dark" content="导出数据">
                <px-button type="primary" text :icon="Document" @click="handleExport23" />
              </px-tooltip>
            </div>
            <div class="model_chart" style="margin-top: 16px">
              <chartswwt2
                ref="chartswwt2Ref"
                :chartvalue="firstPieList"
                style="width: 100%"
                :width="'100%'"
                :height="'270px'"
                @getPieData="setgetPieData"
              />
            </div>
          </div>
        </px-col>
        <px-col :span="12" class="water_col">
          <div class="waterdom borderRidus" style="position: relative">
            <modelTitle :title="'tCO₂e类别统计'" />
            <div class="title-right" style="right: 32px">
              <px-tooltip effect="dark" content="导出图片">
                <px-button type="primary" text :icon="Download" @click="exportImageHandler('chartswwt5Ref')" />
              </px-tooltip>
              <px-tooltip effect="dark" content="导出数据">
                <px-button type="primary" text :icon="Document" @click="handleExport24" />
              </px-tooltip>
            </div>
            <div class="model_chart" style="margin-top: 16px">
              <chartswwt5 ref="chartswwt5Ref" :chartvalue="firstBarList" style="width: 100%" :width="'100%'" :height="'270px'" />
            </div>
          </div>
        </px-col>
      </px-row>
      <px-row style="height: 364px; margin-top: 16px" :gutter="16">
        <px-col :span="8" class="water_col">
          <div class="waterdom borderRidus" style="position: relative">
            <modelTitle :title="'tCO₂e量排行'" />
            <px-button type="primary" style="position: absolute; top: 16px; right: 32px" plain @click="handleExportrank()">导出</px-button>
            <div class="model_chart">
              <px-table
                :data="datavalue.rank"
                style="width: 100%; overflow-x: hidden"
                height="300"
                border
                :row-class-name="tableRowClassName"
                @row-click="handelRowClick"
              >
                <px-table-column type="index" label="排行" width="60" />
                <px-table-column show-overflow-tooltip :tooltip-effect="'light'" prop="facilityName" label="设施活动名称" />
                <px-table-column prop="carbonEmission" label="碳排放量(tCO₂e)" />
                <!-- <px-table-column prop="ratio" label="占比(%)" /> -->
                <px-table-column label="占比(%)" prop="cycle">
                  <template #default="scope">
                    <span>{{ scope.row.ratio ? `${scope.row.ratio}%` : "-" }}</span>
                  </template>
                </px-table-column>
              </px-table>
            </div>
          </div>
        </px-col>
        <px-col :span="16" class="water_col">
          <div class="waterdom borderRidus" style="position: relative">
            <modelTitle :title="'设施活动tCO₂e分析'" />
            <div class="title-right" style="right: 32px">
              <px-tooltip effect="dark" content="导出图片">
                <px-button type="primary" text :icon="Download" @click="exportImageHandler('chartswwt6Ref')" />
              </px-tooltip>
              <px-tooltip effect="dark" content="导出数据">
                <px-button type="primary" text :icon="Document" @click="handleExport" />
              </px-tooltip>
            </div>
            <div class="model_chart" style="margin-top: 16px">
              <chartswwt6
                ref="chartswwt6Ref"
                :dimension="queryParams.dimension"
                :chartvalue="FacilityAnalysisLineBardata"
                style="width: 100%"
                :width="'100%'"
                :height="'270px'"
              />
            </div>
          </div>
        </px-col>
      </px-row>
    </div>
    <div v-if="activeWater == 'fore'">
      <px-row style="height: 340px; margin-top: 16px" :gutter="16">
        <px-col :span="12" class="water_col">
          <div class="waterdom borderRidus" style="position: relative">
            <modelTitle :title="'厂区tCO₂e对比'" />
            <div class="title-right" style="right: 32px">
              <px-tooltip effect="dark" content="导出图片">
                <px-button type="primary" text :icon="Download" @click="exportImageHandler('chartswwt1Ref')" />
              </px-tooltip>
              <px-tooltip effect="dark" content="导出数据">
                <px-button type="primary" text :icon="Document" @click="handleExport21('厂区碳排放量统计')" />
              </px-tooltip>
            </div>
            <div class="model_chart" style="margin-top: 16px">
              <chartswwt1 ref="chartswwt1Ref" :chartvalue="datavalue.statistics" style="width: 100%" :width="'100%'" :height="'270px'" />
            </div>
          </div>
        </px-col>
        <px-col :span="12" class="water_col">
          <div class="waterdom borderRidus" style="position: relative">
            <modelTitle :title="'单位产量tCO₂e对比'" />
            <div class="title-right" style="right: 32px">
              <px-tooltip effect="dark" content="导出图片">
                <px-button type="primary" text :icon="Download" @click="exportImageHandler('chartswwt8Ref')" />
              </px-tooltip>
              <px-tooltip effect="dark" content="导出数据">
                <px-button type="primary" text :icon="Document" @click="handleExport42" />
              </px-tooltip>
            </div>
            <div class="model_chart" style="margin-top: 16px">
              <chartswwt8 ref="chartswwt8Ref" :chartvalue="foreTwoData" style="width: 100%" :width="'100%'" :height="'270px'" />
            </div>
          </div>
        </px-col>
      </px-row>
      <px-row style="height: 364px; margin-top: 16px" :gutter="16">
        <px-col :span="12" class="water_col">
          <div class="waterdom borderRidus" style="position: relative">
            <modelTitle :title="'tCO₂e排放类别对比'" />
            <!-- <px-button type="primary" style="position: absolute; top: 16px; right: 32px" plain @click="handleExportfore3('厂区碳排放量统计')"
              >导出</px-button
            > -->
            <px-button v-show="foreDataflg" style="position: absolute; top: 20px; right: 100px" size="small" type="primary" plain @click="gobackfore1"
              >返回</px-button
            >
            <px-button
              v-show="foreDataflg2"
              style="position: absolute; top: 20px; right: 100px"
              size="small"
              type="primary"
              plain
              @click="gobackfore2"
              >返回</px-button
            >
            <px-button
              v-show="foreDataflg3"
              style="position: absolute; top: 20px; right: 100px"
              size="small"
              type="primary"
              plain
              @click="gobackfore3"
              >返回</px-button
            >
            <div class="model_chart" style="margin-top: 16px">
              <px-table v-if="!foretable2" :data="ComparisonList" height="270" border>
                <px-table-column show-overflow-tooltip align="center" :tooltip-effect="'light'" prop="category" label="排放类别" />
                <!-- <px-table-column prop="carbonEmission" label="碳排放量(tCO₂e)" width="170" /> -->
                <!-- <px-table-column prop="ratio" label="占比(%)" /> -->
                <px-table-column align="center" label="创新中心一期">
                  <template #default="scope">
                    <span class="tablespan">{{ scope.row.ecarbon1 ? `${scope.row.ecarbon1}` : "-" }}</span>
                    <span class="tablespan2">{{ scope.row.ratio1 ? `${scope.row.ratio1}%` : "-" }}</span>
                  </template>
                </px-table-column>
                <px-table-column align="center" label="创新中心二期">
                  <template #default="scope">
                    <span class="tablespan">{{ scope.row.ecarbon2 ? `${scope.row.ecarbon2}` : "-" }}</span>
                    <span class="tablespan2">{{ scope.row.ratio2 ? `${scope.row.ratio2}%` : "-" }}</span>
                  </template>
                </px-table-column>
                <px-table-column fixed="right" label="操作" align="center" width="140">
                  <template #default="scope">
                    <px-button link type="primary" @click="compare(scope.row.category)"> 对比 </px-button>
                    <px-button link type="primary" @click="foreDetail(scope.row)"> 明细 </px-button></template
                  >
                </px-table-column>
              </px-table>
              <px-table v-else :data="foretable2Data" height="270" border :row-class-name="tableRowClassName2" @row-click="handelRowClick2">
                <px-table-column type="index" width="50" label="排行" />
                <px-table-column show-overflow-tooltip align="center" :tooltip-effect="'light'" prop="level" label="厂区" />
                <px-table-column prop="facilityName" align="center" label="设施活动名称" />
                <px-table-column prop="carbonEmission" align="center" label="碳排放量（tCO₂e）" />
                <px-table-column prop="ratio" align="center" label="占比">
                  <template #default="scope">
                    <span>{{ scope.row.ratio ? `${scope.row.ratio}%` : "-" }}</span>
                  </template>
                </px-table-column>
                <!-- <px-table-column prop="ratio" label="占比(%)" /> -->
              </px-table>
            </div>
          </div>
        </px-col>
        <px-col :span="12" class="water_col">
          <div class="waterdom borderRidus" style="position: relative">
            <modelTitle :title="`tCO₂e趋势${fore4name ? `(${fore4name})` : ''}`" />
            <!-- <px-button type="primary" style="position: absolute; top: 16px; right: 32px" plain @click="handleExport42">导出</px-button> -->
            <div class="title-right" style="right: 32px">
              <px-tooltip effect="dark" content="导出图片">
                <px-button type="primary" text :icon="Download" @click="exportImageHandler('chartswwtRef')" />
              </px-tooltip>
              <!-- <px-tooltip effect="dark" content="导出数据">
                <px-button type="primary" text :icon="Document" @click="handleExport42" />
              </px-tooltip> -->
            </div>
            <div class="model_chart" style="margin-top: 16px">
              <chartswwt
                v-if="!foretable2 && ComparisonList.length > 0"
                ref="chartswwtRef"
                :chartvalue="fore4Data"
                style="width: 100%"
                :width="'100%'"
                :height="'292px'"
              />
              <forecharts
                v-if="foretable2 && ComparisonList.length > 0 && fore4chartsData"
                :chartvalue="fore4chartsData"
                style="width: 100%"
                :width="'100%'"
                :height="'292px'"
              />
              <div v-if="ComparisonList.length < 1">
                <px-empty :image-size="50" />
              </div>
            </div>
          </div>
        </px-col>
      </px-row>
    </div>
  </div>
</template>
<script setup lang="ts">
import { Plus, Minus } from "@px-ui/icons-vue";
import { PxMessage, PxMessageBox } from "px-ui";
import modelTitle from "@/views/common/components/modelTitle/index.vue";
import visual from "../visual/index.vue";
import chartsParent from "./components/chartsParent.vue";
import chartswwt from "./components/chartswwt.vue";
import forecharts from "./components/forecharts.vue";
import chartswwt1 from "./components/chartswwt1.vue";
import chartswwt2 from "./components/chartswwt2.vue";
import chartswwt8 from "./components/chartswwt8.vue";
import chartswwt4 from "./components/chartswwt4.vue";
import chartswwt4bottom from "./components/chartswwt4bottom.vue";
import chartswwt5 from "./components/chartswwt5.vue";
import chartswwt6 from "./components/chartswwt6.vue";
import chartswwt7 from "./components/chartswwt7.vue";
import chartsFacility from "./components/chartsFacility.vue";
import chartsUpwChemistry from "./components/chartsUpwChemistry.vue";
import yearPicker from "@/views/common/energy/components/yearPicker.vue";
import chartsIndexUpw from "./components/chartsIndexUpw.vue";
import * as XLSX from "xlsx/xlsx.mjs";
import { accountingTemplatequery } from "@/api/doubleCarbonManage/accountingBoundary";
import { accountingEmissionDatagetEmissionVisual } from "@/api/doubleCarbonManage/visual";
import { getCurrentInstance, ref, toRefs, reactive, onMounted } from "vue";
import {
  accountingEmissionDatagetEmissionAnalysis,
  accountingEmissionDatatraceability,
  accountingEmissionDatagetFacilityAnalysisPie,
  accountingEmissionDatagetFacilityAnalysisLine,
  accountingEmissionDatagetCategoryPieBar,
  accountingEmissionDatagetFacilityAnalysisLineBar,
  accountingEmissionDatagetProductionStatisticTrend,
  accountingEmissionDatagetFactoryEmission,
  accountingEmissionDatagetCategoryEmissionYoy,
  accountingEmissionDatagetProductionFactoryTrend,
  accountingEmissionDatagetFacilityRank,
  accountingEmissionDatagetFactoryCategoryComparisonList,
  accountingEmissionDatagetFactoryCategoryComparisonTrend,
  accountingEmissionDataemissionTrend,
  accountingEmissionDataemissionTrendByFacilityName
} from "@/api/doubleCarbonManage/dataAnalysis";
import { Download, Document } from "@px-ui/icons-vue";
import { exportCanvasImg } from "@/utils/common";

const dateValue = ref<any>({ startYear: new Date().getFullYear() - 2, endYear: new Date().getFullYear() });
const activeWater = ref("first");
const activeWater2 = ref("first");
const foreDataflg = ref(false);
const foreDataflg2 = ref(false);
const foretable2 = ref(false);
const radio3 = ref("全部");
const disabledDate = time => {
  // console.log(time);

  // if (queryParams.value.Time1 && queryParams.value.Time1[0]) {
  //    const year = new Date( queryParams.value.Time1[0])
  //   return time.getFullYear() !== year &&time.getFullYear() < 2023;
  // }
  return time.getFullYear() < 2023;
};
const updateStatisticYear: any = (startYear: number, endYear: number) => {
  console.log("选中年份", startYear, endYear);
  queryParams.value.Time = [startYear.toString(), endYear.toString()];
  queryParams.value.startDate = `${startYear}-01-01 00:00:00`;
  queryParams.value.endDate = `${endYear}-12-31 23:59:59`;
};
const fore4name = ref("");
const oldComparisonList = ref([]);
const gobackfore1 = () => {
  fore4name.value = ComparisonList.value[0].category;
  foreDataflg.value = false;
  ComparisonList.value = oldComparisonList.value;
};
const gobackfore2 = () => {
  fore4name.value = ComparisonList.value[0].category;
  foreDataflg2.value = false;
  foreDataflg.value = true;
};
const foreDataflg3 = ref(false);
const gobackfore3 = () => {
  fore4name.value = ComparisonList.value[0].category;
  foreDataflg3.value = false;
  foreDataflg2.value = true;
  foretable2.value = false;
};
const foretable2Data = ref([]);
const fore4chartsData = ref({});
const forebottomData = ref({});
const foreDetail = row => {
  console.log(row);
  if (foreDataflg.value) {
    if (row.facilityId != null) {
      accountingEmissionDataemissionTrend({
        dimension: queryParams.value.dimension,
        startDate: queryParams.value.startDate,
        endDate: queryParams.value.endDate,
        level: queryParams.value.lev,
        templateId: queryParams.value.templateId,
        relationIds: row.facilityId
      }).then(res => {
        foretable2.value = true;
        foreDataflg3.value = true;
        console.log(res);
        foretable2Data.value = res.emissionRankingDataDTOList[0].emissionRankingDTOList;
        console.log(foretable2Data.value);
        selectRow2.value = foretable2Data.value[0];
        // fore4chartsData.value = res.trendDataDTOList[0];
        fore4name.value = foretable2Data.value[0].facilityName;
      });
      accountingEmissionDataemissionTrendByFacilityName({
        dimension: queryParams.value.dimension,
        startDate: queryParams.value.startDate,
        endDate: queryParams.value.endDate,
        level: queryParams.value.lev,
        templateId: queryParams.value.templateId,
        facilityName: row.facilityName
      }).then(res => {
        console.log(res);
        forebottomData.value = res;
        fore4chartsData.value = res.trendDataDTOList.find(e => e.facilityName == fore4name.value);
      });
    } else {
      PxMessage({
        message: `暂无明细`,
        type: "error"
      });
    }
  } else {
    accountingEmissionDatagetFactoryCategoryComparisonList({
      dimension: queryParams.value.dimension,
      startDate: queryParams.value.startDate,
      endDate: queryParams.value.endDate,
      level: queryParams.value.lev,
      templateId: queryParams.value.templateId,
      categoryName: row.category
    }).then(res => {
      console.log(res);
      ComparisonList.value = res.category;
      foreDataflg.value = true;
      compare(ComparisonList.value[0].category);
    });
  }
};
const compare = name => {
  console.log(name);
  fore4name.value = name;
  accountingEmissionDatagetFactoryCategoryComparisonTrend({
    dimension: queryParams.value.dimension,
    startDate: queryParams.value.startDate,
    endDate: queryParams.value.endDate,
    level: queryParams.value.lev,
    templateId: queryParams.value.templateId,
    categoryName: name
  }).then(res => {
    console.log(res);
    fore4Data.value = res.childCategory;
  });
};
const imgscale = ref(1);
const bigimg = () => {
  if (imgscale.value < 1.9) {
    imgscale.value = imgscale.value + 0.1;
  }
};
const smailimg = () => {
  if (imgscale.value > 0.4) {
    imgscale.value = imgscale.value - 0.1;
  }
};
const onWheel = event => {
  event.preventDefault();
  if (event.deltaY < 0) {
    imgscale.value = imgscale.value + 0.1;
  } else {
    imgscale.value = imgscale.value - 0.1;
  }
  // 限制缩放比例范围
  imgscale.value = Math.min(Math.max(imgscale.value, 0.1), 2.0);
  // 更新 initialScale 以保持拖拽位置正确
  // initialScale = imgscale.value;
};
const setgetPieData = val => {
  console.log(val);
  if (val && val.label == "1") {
    firstDataflg.value = true;
    twoDataflg.value = false;
    firstPieList.value = firstData.value.childCategoryList.filter(item => item.category == val.name)[0].childCategory;
    firstBarList.value = firstData.value.childCategoryBarList.filter(item => item.category == val.name)[0].childCategory;
    getrank1(val.name);
  }
  if (val && val.label == "2") {
    firstDataflg.value = false;
    twoDataflg.value = true;
    oldfirstPieList.value = firstPieList.value;
    oldfirstBarList.value = firstBarList.value;
    firstPieList.value = firstData.value.facilityList.filter(item => item.category == val.name)[0].childCategory;
    firstBarList.value = firstData.value.facilityBarList.filter(item => item.category == val.name)[0].childCategory;
    getrank1(val.name);
  }
};
const getrank1 = name => {
  accountingEmissionDatagetFacilityRank({
    dimension: queryParams.value.dimension,
    startDate: queryParams.value.startDate,
    endDate: queryParams.value.endDate,
    level: queryParams.value.lev,
    templateId: queryParams.value.templateId,
    categoryName: name
  }).then(res => {
    datavalue.value = res;
    if (res != null) {
      selectRow.value = res.rank[0];
      accountingEmissionDatagetFacilityAnalysisLineBar({
        facilityName: res.rank[0]?.facilityName,
        dimension: queryParams.value.dimension,
        startDate: queryParams.value.startDate,
        endDate: queryParams.value.endDate,
        level: queryParams.value.lev,
        templateId: queryParams.value.templateId
      }).then(res => {
        console.log(res);
        FacilityAnalysisLineBardata.value = res;
      });
    } else {
      datavalue.value.emissionRankingAnalysisDTOS = [];
    }
  });
};
const getrank2 = () => {
  accountingEmissionDatagetFacilityRank({
    dimension: queryParams.value.dimension,
    startDate: queryParams.value.startDate,
    endDate: queryParams.value.endDate,
    level: queryParams.value.lev,
    templateId: queryParams.value.templateId
  }).then(res => {
    datavalue.value = res;
    if (res != null) {
      selectRow.value = res.rank[0];
      accountingEmissionDatagetFacilityAnalysisLineBar({
        facilityName: res.rank[0]?.facilityName,
        dimension: queryParams.value.dimension,
        startDate: queryParams.value.startDate,
        endDate: queryParams.value.endDate,
        level: queryParams.value.lev,
        templateId: queryParams.value.templateId
      }).then(res => {
        console.log(res);
        FacilityAnalysisLineBardata.value = res;
      });
    } else {
      datavalue.value.emissionRankingAnalysisDTOS = [];
    }
  });
};
const { proxy }: any = getCurrentInstance();
const handleExport = () => {
  proxy.download("post", "/energy/accountingEmissionData/exportFacilityAnalysisLineBar", FacilityAnalysisLineBardata.value);
};
const handleExport21 = name => {
  datavalue.value.name = name;
  proxy.download("post", "/energy/accountingEmissionData/exportEmissionAnalysis", datavalue.value);
};
const handleExport23 = () => {
  firstData.value.name = "tCO₂e类别占比";
  firstData.value.type = "pie";
  proxy.download("post", "/energy/accountingEmissionData/exportCategoryPieBar", firstData.value);
};
const handleExportall = () => {
  proxy.download("post", "/energy/accountingEmissionData/exportFactoryEmission", allData.value);
};
const handleExportavg = () => {
  proxy.download("post", "/energy/accountingEmissionData/exportProductionStatisticTrend", avgData.value);
};
const handleExportrank = () => {
  proxy.download("post", "/energy/accountingEmissionData/exportFacilityRank", datavalue.value);
};
const handleExport24 = () => {
  firstData.value.name = null;
  firstData.value.type = "bar";
  proxy.download("post", "/energy/accountingEmissionData/exportCategoryPieBar", firstData.value);
};
const handleExport31 = () => {
  firstData.value.name = null;
  firstData.value.type = "bar";
  proxy.download("post", "/energy/accountingEmissionData/exportTraceability", {
    startDate: queryParams.value.startDate,
    endDate: queryParams.value.endDate,
    templateId: queryParams.value.templateId,
    level: queryParams.value.lev
  });
};
const handleExport42 = () => {
  proxy.download("post", "/energy/accountingEmissionData/exportProductionFactoryTrend", foreTwoData.value);
};
const handleExportfore3 = () => {
  proxy.download("post", "/energy/accountingEmissionData/exportProductionFactoryTrend", foreTwoData.value);
};
const selectRow = ref(null);
const foreTwoData = ref({});
const tableRowClassName = ({ row, rowIndex }) => {
  if (selectRow.value == row) {
    return "row-selected";
  }
  return "";
};
const selectRow2 = ref({});
const tableRowClassName2 = ({ row, rowIndex }) => {
  row.index = rowIndex;
  if (selectRow2.value == row) {
    return "row-selected";
  }
  return "";
};
const handelRowClick = row => {
  console.log(row);
  selectRow.value = row;
  accountingEmissionDatagetFacilityAnalysisLineBar({
    facilityName: row.facilityName,
    dimension: queryParams.value.dimension,
    startDate: queryParams.value.startDate,
    endDate: queryParams.value.endDate,
    level: queryParams.value.lev,
    templateId: queryParams.value.templateId
  }).then(res => {
    console.log(res);
    FacilityAnalysisLineBardata.value = res;
  });
};
const handelRowClick2 = row => {
  console.log(row);
  selectRow2.value = row;
  fore4name.value = row.facilityName;
  fore4chartsData.value = forebottomData.value.trendDataDTOList.filter(item => item.facilityName == row.facilityName)[0];
  // accountingEmissionDatagetFacilityAnalysisLineBar({
  //   facilityName: row.facilityName,
  //   dimension: queryParams.value.dimension,
  //   startDate: queryParams.value.startDate,
  //   endDate: queryParams.value.endDate,
  //   level: queryParams.value.lev,
  //   templateId: queryParams.value.templateId
  // }).then(res => {
  //   console.log(res);
  //   FacilityAnalysisLineBardata.value = res;
  // });
};
const gobackpiedata = () => {
  firstDataflg.value = false;
  firstPieList.value = firstData.value.category;
  firstBarList.value = firstData.value.categoryBar;
  getrank2();
};
const gobackpiedata2 = () => {
  twoDataflg.value = false;
  firstDataflg.value = true;
  firstPieList.value = oldfirstPieList.value;
  firstBarList.value = oldfirstBarList.value;
  // console.log(firstPieList.value);
  getrank1(firstPieList.value[0].name);
};
const tabPaneList = [
  // {
  //   label: "碳排放总览",
  //   name: "visual"
  // },
  {
    label: "碳排放分析",
    name: "first"
  },
  {
    label: "碳排放溯源",
    name: "two"
  },
  {
    label: "碳排放类别分析",
    name: "three"
  },
  {
    label: "碳排放厂区对比",
    name: "fore"
  }
];
const tabPaneList2 = [
  {
    label: "碳排放量",
    name: "first"
  },
  {
    label: "环比",
    name: "two"
  },
  {
    label: "同比",
    name: "three"
  }
];
const foredisbled = ref(false);
const setactive = val => {
  console.log(val);
  if (val == "fore") {
    foredisbled.value = true;
    queryParams.value.lev = null;
    if (localStorage.getItem("facList")) {
      let faclist = JSON.parse(localStorage.getItem("facList"));
      if (faclist.length == 1) {
        foredisbled.value = true;
        queryParams.value.lev = faclist[0].name;
      } else if (faclist.length == 2) {
        foredisbled.value = true;
        queryParams.value.lev = null;
      }
    }
  } else {
    foredisbled.value = false;
    if (localStorage.getItem("facList")) {
      let faclist = JSON.parse(localStorage.getItem("facList"));
      if (faclist.length == 1) {
        foredisbled.value = true;
        queryParams.value.lev = faclist[0].name;
      } else if (faclist.length == 2) {
        foredisbled.value = false;
        // queryParams.value.lev = null
      }
    }
  }
  getList();
};
const setdimension = val => {
  console.log(val);
  if (val == "Y") {
    queryParams.value.startDate = `${dateValue.value.startYear}-01-01 00:00:00`;
    queryParams.value.endDate = `${dateValue.value.endYear}-12-31 23:59:59`;
  } else {
    const res = getMonthRange(queryParams.value.Time1);
    queryParams.value.startDate = res[0];
    queryParams.value.endDate = res[1];
  }
  // getList();
};
function formatDate(date) {
  const pad = num => num.toString().padStart(2, "0");
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
}

function getMonthRange(months) {
  const [startMonth, endMonth] = months;

  // 解析起始月份（第一个月的第一天 00:00:00）
  const [startYear, startMonthNum] = startMonth.split("-").map(Number);
  const startDate = new Date(startYear, startMonthNum - 1, 1, 0, 0, 0);

  // 解析结束月份（最后一天 23:59:59）
  const [endYear, endMonthNum] = endMonth.split("-").map(Number);
  const endDate = new Date(endYear, endMonthNum, 0, 23, 59, 59); // 下个月的第 0 天 = 这个月的最后一天

  return [formatDate(startDate), formatDate(endDate)];
}
const setactive2 = val => {
  console.log(val);
  if (val == "first") {
    console.log(AnalysisLineData.value.cur);
    if (AnalysisLineData.value.cur != null) {
      lineList.value = AnalysisLineData.value.cur;
      if (AnalysisLineData.value.cur != null) {
        lineList.value = AnalysisLineData.value.cur;
        radio3.value = AnalysisLineData.value.cur[0].category;
        lineListcharts.value = AnalysisLineData.value.cur[0].facility;
      }
    } else {
      lineList.value = [];
      lineListcharts.value = null;
    }
  }
  if (val == "two") {
    if (AnalysisLineData.value.mom != null) {
      lineList.value = AnalysisLineData.value.mom;
      if (AnalysisLineData.value.mom != null) {
        lineList.value = AnalysisLineData.value.mom;
        radio3.value = AnalysisLineData.value.mom[0].category;
        lineListcharts.value = AnalysisLineData.value.mom[0].facility;
      }
    } else {
      lineList.value = [];
      lineListcharts.value = null;
    }
  }
  if (val == "three") {
    if (AnalysisLineData.value.yoy != null) {
      lineList.value = AnalysisLineData.value.yoy;
      if (AnalysisLineData.value.yoy != null) {
        lineList.value = AnalysisLineData.value.yoy;
        radio3.value = AnalysisLineData.value.yoy[0].category;
        lineListcharts.value = AnalysisLineData.value.yoy[0].facility;
      }
    } else {
      lineList.value = [];
      lineListcharts.value = null;
    }
  }
};
const exportToExcel = () => {
  // 创建一个工作簿
  const wb = XLSX.utils.book_new();

  // 转换json到工作表
  let wsData = [
    ["排行", "设施活动名称", "碳排放量(tCO₂e)", "占比"],
    ...datavalue.value.emissionRankingAnalysisDTOS.map(item => [item.taskNo, item.taskName, item.responsible, item.status])
  ];
  console.log(wsData);
  const ws = XLSX.utils.json_to_sheet(wsData);

  // 添加工作表到工作簿
  XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

  // 生成excel文件的blob对象
  const wbout = XLSX.write(wb, { bookType: "xlsx", type: "binary" });

  // 创建一个临时的a标签用于下载
  const blob = new Blob([s2ab(wbout)], { type: "application/octet-stream" });

  // 创建一个指向文件的URL
  const url = window.URL.createObjectURL(blob);

  // 创建一个a标签并模拟点击进行下载
  const link = document.createElement("a");
  link.href = url;
  link.setAttribute("download", "碳排放量排行.xlsx");
  document.body.appendChild(link);
  link.click();

  // 清理工作
  window.URL.revokeObjectURL(url);
  document.body.removeChild(link);

  // 字符串转ArrayBuffer
  function s2ab(s) {
    const buf = new ArrayBuffer(s.length);
    const view = new Uint8Array(buf);
    for (let i = 0; i < s.length; i++) {
      view[i] = s.charCodeAt(i) & 0xff;
    }
    return buf;
  }
};
const getlastday = date => {
  date.setMonth(date.getMonth() + 1, 1);
  date.setDate(date.getDate() - 1);
  return date.getDate();
};
const settime = val => {
  console.log(val);
  var today = new Date(val[1]);
  if (val[0].slice(0, 4) == val[1].slice(0, 4)) {
    queryParams.value.startDate = `${val[0]}-01 00:00:00`;
    queryParams.value.endDate = `${val[1]}-${getlastday(today)} 23:59:59`;
  } else {
    queryParams.value.Time1 = [queryParams.value.startDate.slice(0, 7), queryParams.value.endDate.slice(0, 7)];
    PxMessage({
      message: "月份不支持跨年搜索",
      type: "error"
    });
  }
};
const settime2 = val => {
  console.log(val);
  queryParams.value.startDate = val[0];
  queryParams.value.endDate = val[1];
};
const radiochange = val => {
  console.log(val);
  if (activeWater2.value == "first") {
    if (AnalysisLineData.value.cur.filter(item => item.category == val)[0]?.facility != null) {
      lineListcharts.value = AnalysisLineData.value.cur.filter(item => item.category == val)[0]?.facility;
    } else {
      lineListcharts.value = [];
    }
  }
  if (activeWater2.value == "two") {
    if (AnalysisLineData.value.cur.filter(item => item.category == val)[0]?.facility != null) {
      lineListcharts.value = AnalysisLineData.value.mom.filter(item => item.category == val)[0]?.facility;
    } else {
      lineListcharts.value = [];
    }
  }
  if (activeWater2.value == "three") {
    if (AnalysisLineData.value.cur.filter(item => item.category == val)[0]?.facility != null) {
      lineListcharts.value = AnalysisLineData.value.yoy.filter(item => item.category == val)[0]?.facility;
    } else {
      lineListcharts.value = [];
    }
  }
};
const data = reactive({
  sanjiValue: {},
  dimensionList: [
    {
      itemName: "月度",
      itemValue: "M"
    },
    {
      itemName: "年度",
      itemValue: "Y"
    }
  ],
  datavalue: {
    rank: []
  },
  queryParams: {
    dimension: "M",
    startDate: "",
    endDate: "",
    Time1: [],
    Time2: [],
    lev: null,
    templateId: ""
  },
  tableData: [
    {
      taskNo: "1",
      taskName: "外购热",
      responsible: "159916.67",
      status: "78.64%"
    },
    {
      taskNo: "2",
      taskName: "外购电",
      responsible: "27333.37",
      status: "13.44%"
    },
    {
      taskNo: "3",
      taskName: "固定资产生产设备类",
      responsible: "15274.55",
      status: "7.51%"
    },
    {
      taskNo: "4",
      taskName: "废气燃烧装置",
      responsible: "503.93",
      status: "0.25%"
    },
    {
      taskNo: "5",
      taskName: "ETCH-SF6",
      responsible: "170.10",
      status: "0.08%"
    }
  ],
  typeList: [],
  AnalysisPieDate: {
    category: [],
    childCategory: [],
    facility: []
  },
  AnalysisLineData: {
    cur: [],
    mom: [],
    yoy: []
  },
  lineList: [],
  lineListcharts: [],
  visualData: {
    facility: [],
    sumCur: "",
    sumRatio: "",
    category: []
  },
  firstPieList: [],
  firstBarList: [],
  oldfirstPieList: [],
  oldfirstBarList: [],
  firstData: {},
  firstDataflg: false,
  twoDataflg: false,
  FacilityAnalysisLineBardata: {},
  ComparisonList: []
});
const liquidList = [
  {
    itemName: "全厂",
    itemValue: null
  },
  {
    itemName: "创新中心一期",
    itemValue: "创新中心一期"
  },
  {
    itemName: "创新中心二期",
    itemValue: "创新中心二期"
  }
];
const {
  ComparisonList,
  oldfirstPieList,
  oldfirstBarList,
  twoDataflg,
  FacilityAnalysisLineBardata,
  firstDataflg,
  firstData,
  firstPieList,
  firstBarList,
  visualData,
  lineList,
  lineListcharts,
  queryParams,
  typeList,
  datavalue,
  dimensionList,
  sanjiValue,
  AnalysisPieDate,
  AnalysisLineData
} = toRefs(data);
let facDisabled = ref(false);
onMounted(() => {
  if (queryParams.value.dimension == "Y") {
    queryParams.value.startDate = `${new Date().getFullYear() - 4}-01-01 00:00:00`;
    queryParams.value.endDate = `${new Date().getFullYear()}-12-31 23:59:59`;
    // getList();
  } else {
    if (new Date().getMonth() == 0) {
      queryParams.value.startDate = `${new Date().getFullYear() - 1}-01-01 00:00:00`;
      queryParams.value.endDate = `${new Date().getFullYear() - 1}-12-31 23:59:59`;
      queryParams.value.Time1 = [`${new Date().getFullYear() - 1}-01`, `${new Date().getFullYear() - 1}-12`];
      // getList();
    } else {
      queryParams.value.startDate = `${new Date().getFullYear()}-01-01 00:00:00`;
      queryParams.value.endDate = `${new Date().getFullYear()}-12-31 23:59:59`;
      queryParams.value.Time1 = [`${new Date().getFullYear()}-01`, `${new Date().getFullYear()}-12`];
      // getList();
    }
  }
  accountingTemplatequery({
    orderByColumn: "",
    isAsc: "",
    templateName: "",
    templateStatus: "",
    orderBy: "",
    pageNum: 1,
    pageSize: 999
  }).then((response: any) => {
    typeList.value = response.data.filter(item => item.templateStatus != "禁用");
    queryParams.value.templateId = typeList.value[0]?.id;
    if (localStorage.getItem("facList")) {
      let faclist = JSON.parse(localStorage.getItem("facList"));
      if (faclist.length == 1) {
        foredisbled.value = true;
        queryParams.value.lev = faclist[0].name;
        getList();
      } else if (faclist.length == 2) {
        foredisbled.value = false;
        queryParams.value.lev = null;
        getList();
      }
    }
  });
});
const handleQuery = () => {
  getList();
};
const resetQuery = () => {
  queryParams.value.startDate = `${new Date().getFullYear()}-01-01 00:00:00`;
  queryParams.value.endDate = `${new Date().getFullYear()}-12-31 23:59:59`;
  queryParams.value.Time1 = [`${new Date().getFullYear()}-01`, `${new Date().getFullYear()}-12`];
  queryParams.value.dimension = "M";
  queryParams.value.lev = null;
  queryParams.value.templateId = typeList.value[0]?.id;
  if (localStorage.getItem("facList")) {
    let faclist = JSON.parse(localStorage.getItem("facList"));
    if (faclist.length == 1) {
      foredisbled.value = true;
      queryParams.value.lev = faclist[0].name;
      getList();
    } else if (faclist.length == 2) {
      foredisbled.value = false;
      queryParams.value.lev = null;
      getList();
    }
  }
};
const avgData = ref({});
const allData = ref({});
const firstCenterData = ref([]);
const fore4Data = ref({});
const getList = () => {
  if (activeWater.value == "visual") {
    accountingEmissionDatagetEmissionVisual({
      startDate: queryParams.value.startDate,
      endDate: queryParams.value.endDate,
      level: queryParams.value.lev,
      templateId: queryParams.value.templateId
    }).then(res => {
      console.log(res);
      if (res != null) {
        visualData.value = res;
      } else {
        visualData.value = {
          facility: [],
          sumCur: "",
          sumRatio: "",
          category: []
        };
      }
    });
  }
  if (activeWater.value == "first") {
    accountingEmissionDatagetProductionStatisticTrend({
      dimension: queryParams.value.dimension,
      startDate: queryParams.value.startDate,
      endDate: queryParams.value.endDate,
      level: queryParams.value.lev,
      templateId: queryParams.value.templateId
    }).then(res => {
      avgData.value = res;
    });
    accountingEmissionDatagetCategoryEmissionYoy({
      dimension: queryParams.value.dimension,
      startDate: queryParams.value.startDate,
      endDate: queryParams.value.endDate,
      level: queryParams.value.lev,
      templateId: queryParams.value.templateId
    }).then(res => {
      firstCenterData.value = res;
      console.log(res);
    });
    accountingEmissionDatagetFactoryEmission({
      dimension: queryParams.value.dimension,
      startDate: queryParams.value.startDate,
      endDate: queryParams.value.endDate,
      level: queryParams.value.lev,
      templateId: queryParams.value.templateId
    }).then(res => {
      console.log(res);
      allData.value = res;
    });
    accountingEmissionDatagetCategoryPieBar({
      dimension: queryParams.value.dimension,
      startDate: queryParams.value.startDate,
      endDate: queryParams.value.endDate,
      level: queryParams.value.lev,
      templateId: queryParams.value.templateId
    }).then(res => {
      console.log(res);
      firstData.value = res;
      if (res != null) {
        firstPieList.value = res.category;
        firstBarList.value = res.categoryBar;
      } else {
        firstPieList.value = [];
        firstBarList.value = [];
      }
    });
  } else if (activeWater.value == "two") {
    accountingEmissionDatatraceability({
      startDate: queryParams.value.startDate,
      endDate: queryParams.value.endDate,
      templateId: queryParams.value.templateId,
      level: queryParams.value.lev
    }).then((response: any) => {
      console.log(response);
      sanjiValue.value = response;
    });
  } else if (activeWater.value == "three") {
    accountingEmissionDatagetFacilityRank({
      dimension: queryParams.value.dimension,
      startDate: queryParams.value.startDate,
      endDate: queryParams.value.endDate,
      level: queryParams.value.lev,
      templateId: queryParams.value.templateId
    }).then(res => {
      datavalue.value = res;
      if (res != null) {
        selectRow.value = res.rank[0];
        accountingEmissionDatagetFacilityAnalysisLineBar({
          facilityName: res.rank[0]?.facilityName,
          dimension: queryParams.value.dimension,
          startDate: queryParams.value.startDate,
          endDate: queryParams.value.endDate,
          level: queryParams.value.lev,
          templateId: queryParams.value.templateId
        }).then(res => {
          console.log(res);
          FacilityAnalysisLineBardata.value = res;
        });
      } else {
        datavalue.value.emissionRankingAnalysisDTOS = [];
      }
    });
    accountingEmissionDatagetCategoryPieBar({
      dimension: queryParams.value.dimension,
      startDate: queryParams.value.startDate,
      endDate: queryParams.value.endDate,
      level: queryParams.value.lev,
      templateId: queryParams.value.templateId
    }).then(res => {
      console.log(res);
      firstData.value = res;
      if (res != null) {
        firstPieList.value = res.category;
        firstBarList.value = res.categoryBar;
      } else {
        firstPieList.value = [];
        firstBarList.value = [];
      }
    });
  } else if (activeWater.value == "fore") {
    foreDataflg.value = false;
    foreDataflg2.value = false;
    foreDataflg3.value = false;
    accountingEmissionDatagetEmissionAnalysis({
      dimension: queryParams.value.dimension,
      startDate: queryParams.value.startDate,
      endDate: queryParams.value.endDate,
      level: queryParams.value.lev,
      templateId: queryParams.value.templateId
    }).then(res => {
      console.log(res);
      datavalue.value = res;
      if (res.emissionRankingAnalysisDTOS != null) {
        datavalue.value.emissionRankingAnalysisDTOS = res.emissionRankingAnalysisDTOS;
      } else {
        datavalue.value.emissionRankingAnalysisDTOS = [];
      }
    });
    accountingEmissionDatagetProductionFactoryTrend({
      dimension: queryParams.value.dimension,
      startDate: queryParams.value.startDate,
      endDate: queryParams.value.endDate,
      level: queryParams.value.lev,
      templateId: queryParams.value.templateId
    }).then(res => {
      foreTwoData.value = res;
      console.log(res);
    });
    accountingEmissionDatagetFactoryCategoryComparisonList({
      dimension: queryParams.value.dimension,
      startDate: queryParams.value.startDate,
      endDate: queryParams.value.endDate,
      level: queryParams.value.lev,
      templateId: queryParams.value.templateId
    }).then(res => {
      console.log(res);
      ComparisonList.value = res.category;
      foretable2.value = false;
      oldComparisonList.value = res.category;
      fore4name.value = res.category[0]?.category;
      accountingEmissionDatagetFactoryCategoryComparisonTrend({
        dimension: queryParams.value.dimension,
        startDate: queryParams.value.startDate,
        endDate: queryParams.value.endDate,
        level: queryParams.value.lev,
        templateId: queryParams.value.templateId,
        categoryName: res.category[0]?.category
      }).then(res => {
        console.log(res);
        fore4Data.value = res.childCategory;
      });
    });
  }
};
const chartswwt7Ref = ref(null);
const chartswwt7Ref_1 = ref(null);
const chartsUpwChemistryRef = ref(null);
const chartswwt2Ref = ref(null);
const chartswwt5Ref = ref(null);
const chartswwt6Ref = ref(null);
const chartswwt1Ref = ref(null);
const chartswwt8Ref = ref(null);
const chartswwtRef = ref(null);
function exportImageHandler(key: string) {
  const map = {
    chartswwt7Ref: chartswwt7Ref.value?.$el,
    chartswwt7Ref_1: chartswwt7Ref_1.value?.$el,
    chartsUpwChemistryRef: chartsUpwChemistryRef.value?.$el,
    chartswwt2Ref: chartswwt2Ref.value?.$el,
    chartswwt5Ref: chartswwt5Ref.value?.$el,
    chartswwt6Ref: chartswwt6Ref.value?.$el,
    chartswwt1Ref: chartswwt1Ref.value?.$el,
    chartswwt8Ref: chartswwt8Ref.value?.$el,
    chartswwtRef: chartswwtRef.value?.$el
  };
  const canvas = map[key].querySelector("canvas");
  exportCanvasImg(canvas);
}
</script>

<style scoped lang="scss">
.water_col {
  height: 100%;
}

.tablespan {
  display: inline-block;
  width: calc(50% - 1px);
  text-align: center;
  border-right: 1px solid #dcdfe6;
}

.tablespan2 {
  display: inline-block;
  width: 50%;
  text-align: center;
}

.waterdom {
  position: relative;
  width: 100%;
  height: 100%;
  padding: 16px 24px;
  background-color: #fff;
  border-radius: 4px;
}

.first_width {
  width: calc(100% - 16px);
}

.model_chart {
  position: relative;
  width: 100%;
  height: calc(100% - 40px);
  margin-top: 10px;

  .co2img {
    position: absolute;
    top: 32px;
    left: 22px;
    width: 48px;
    height: 48px;
  }

  .titlep {
    position: absolute;
    top: 29px;
    left: 90px;
    font-size: 16px;
    font-weight: 600;
    color: #000;
  }

  .titlevalue {
    position: absolute;
    top: 55px;
    left: 90px;

    .titlevalue1 {
      float: left;
      font-size: 20px;
      font-weight: 600;
      line-height: 28px;
      color: #3b82f6;
    }

    .titlevalue1span {
      font-size: 16px;
      font-weight: 400;
      line-height: 22px;
      color: #4f4f4f;
    }

    .titlevalue2 {
      float: left;
      margin-top: 5px;
      margin-left: 20px;
      font-size: 14px;
      font-weight: 400;
      line-height: 20px;
      color: #000;
    }

    .titlevalue2span {
      display: inline-block;
      margin-left: 8px;
      font-size: 14px;
      line-height: 20px;
      color: #f87171;
    }
  }

  .co2mian {
    position: absolute;
    top: 112px;
    left: 0;
    width: 100%;
    height: 92px;
  }

  .divcolor {
    display: inline-block;
    width: 8px;
    height: 8px;
    margin-right: 16px;
    background: #3b82f6;
    border-radius: 50%;
  }

  .co2mianleft {
    float: left;
    width: 50%;
    height: 100%;

    &:nth-child(1) {
      width: calc(50% - 1px);
      border-right: 1px solid #cbcdd8;
    }

    &:nth-child(2) {
      padding-left: 40px;
    }

    .co2mianleftp {
      width: calc(100% - 21px);
      height: 22px;
      padding-left: 20px;
      font-size: 16px;
      font-weight: 600;
      line-height: 20px;
      color: #000;
      // border-right: 1px solid #cbcdd8;
    }
  }

  .co2mianright {
    float: left;
    width: 50%;
    height: 100%;

    .co2mianrightp {
      width: calc(100% - 45px);
      height: 22px;
      padding-left: 45px;
      font-size: 14px;
      font-weight: 400;
      line-height: 20px;
      color: #000;
    }
  }

  .co2mianleftp2 {
    margin-left: 20px;
    font-size: 16px;
    font-weight: 600;
    color: #3b82f6;

    .co2mianleftp2name {
      display: inline-block;
      width: 70px;
      font-size: 14px;
      font-weight: 400;
      color: black;
    }

    .co2mianleftp2span {
      font-size: 14px;
      font-weight: 400;
      color: #4f4f4f;
    }
  }

  .co2mianleftp3 {
    float: left;
    margin-left: 20px;
    font-size: 14px;
    font-weight: 400;
    color: #000;

    .titlevalue2span {
      display: inline-block;
      margin-left: 8px;
      font-size: 14px;
      line-height: 20px;
      color: #34d399;
    }
  }
}

.percentage-value {
  display: block;
  margin-top: 10px;
  font-size: 26px;
}

.percentage-label {
  display: block;
  margin-top: 10px;
  font-size: 16px;
}

.percentage-value2 {
  display: block;
  margin-top: 10px;
  font-size: 20px;
}

.percentage-label2 {
  display: block;
  margin-top: 10px;
  font-size: 14px;
}

.percentage-value3 {
  display: block;
  margin-top: 10px;
  font-size: 20px;
  color: #f00;
}

.percentage-label3 {
  display: block;
  margin-top: 10px;
  font-size: 14px;
  color: #f00;
}

.jindu1 {
  margin: 24px 0 0 17px;
}

.jindu2 {
  margin: 38px calc((100% - 103px) / 2);
}

.jindu1p {
  width: calc(100% - 24px);
  margin-top: 0;
  font-size: 16px;
  text-align: center;
}

.jindu2p {
  width: 100%;
  margin-top: -40px;
  font-size: 14px;
  text-align: center;
}

:deep(.px-table) {
  .px-table__cell {
    padding: 6px 0;
  }

  td,
  .px-table__header-wrapper,
  .px-table__fixed-header-wrapper {
    th {
      background-color: #f4f4f4 !important;
    }
  }
}

:deep(.px-table--striped .px-table__body tr.px-table__row--striped td.px-table__cell) {
  background-color: rgb(231 238 251 / 50%) !important;
}

:deep(.px-table__inner-wrapper::before) {
  // background: none;
}

.loadicon {
  position: absolute;
  top: 25px;
  right: 25px;
  cursor: pointer;
}

:deep(.custom-form-ui .px-form-item) {
  width: 226px;
}

.fenxi-tabs {
  position: absolute;
  top: 10px;
  left: 330px;
}

:deep(.row-selected) {
  .px-table__cell {
    color: white;
    background: #3b82f6cc !important;
  }
}

.title-right {
  position: absolute;
  top: 16px;
  right: 24px;
  display: flex;
  gap: 16px;
  align-items: center;

  .px-button {
    padding: 0;

    & + .px-button {
      margin-left: 0;
    }
  }
}
</style>
